/**
 * @file 实现缓存
 * @author ly
 * @createDate 2020年4月27日
 */
import React from 'react';
import { useAppSelector, useAppDispatch } from '@/store';
import { SET_KEEPALIVE_DATA, GET_KEEPALIVE_DATA, PayloadType } from '@/store/reducers/keepAlive';

// 存储缓存唯键
export const KeepAliveKeys = new Set<string>();

type KeepAliveDataParams<T> = {
	key: string;
	value: T;
};

/**
 * @param 路径或者自定义别名
 * @returns initKeepAliveData 获取缓存参数
 * @returns setKeepAliveData 修改缓存数据方法
 */
const useKeepAlive = () => {
	const dispatch = useAppDispatch();
	// 获取初始化数据 取出redux数据
	const initValue = useAppSelector(GET_KEEPALIVE_DATA);

	const getKeepAliveData = <T,>(key: string): PayloadType<T>['value'] => {
		return (initValue[key]?.value || {}) as PayloadType<T>['value'];
	};

	const setKeepAliveData = <T extends object>(value: KeepAliveDataParams<T>) => {
		const { key } = value;

		if (!KeepAliveKeys.has(key)) {
			return console.error(`KeepAlive没有key:${key}，本次将不会缓存！`);
		}
		dispatch(SET_KEEPALIVE_DATA(value));
	};

	return { getKeepAliveData, keepAliveAllData: initValue, setKeepAliveData };
};

export default useKeepAlive;
